//
//  LBAddPhotoView.m
//  app
//
//  Created by 杨庆人 on 16/12/20.
//  Copyright © 2016年 广东联结电子商务有限公司. All rights reserved.
//

#import "LBAddPhotoView.h"
#import <UICollectionViewLeftAlignedLayout/UICollectionViewLeftAlignedLayout.h>
#import "LBUploadPhotoCell.h"
#import <LBUIKit/LBPhotoBrowser.h>
#import "LBTaskPhotoCell.h"
#import "LBAddQualifiedBsCell.h"
#import <Masonry/Masonry.h>
#import <LBCategory/LBCategory.h>
#import <LBLoadingView/LBLoadingView.h>
#import <AssetsLibrary/ALAsset.h>
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <AssetsLibrary/ALAssetsGroup.h>
#import <AssetsLibrary/ALAssetRepresentation.h>

static CGFloat const minimumLineSpacing = 10;
static CGFloat const minimumInteritemSpacing = 10;

@interface LBAddPhotoView ()<UICollectionViewDataSource,UICollectionViewDelegate> {
    
    CGSize _itemSize;
    CGFloat _left;
    CGFloat _right;
}


@property (nonatomic,strong)UICollectionView * collectionView;
@property (nonatomic,strong)UICollectionViewLeftAlignedLayout * flowLayout;
@property (nonatomic,assign)LBServiceOSSCode OSSCode;
@property (nonatomic,copy)NSString * itemName;
@property (nonatomic,assign)NSInteger maxCount;
@property (nonatomic,assign)LBAddPhotoViewType photoViewType;
@property (nonatomic,assign)BOOL unEditable;
@end
@implementation LBAddPhotoView

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _flowLayout = [[UICollectionViewLeftAlignedLayout alloc] init];
        _flowLayout.sectionInset = UIEdgeInsetsMake(0, _left, 0, _right);
        _flowLayout.minimumLineSpacing = minimumLineSpacing;
        _flowLayout.minimumInteritemSpacing = minimumInteritemSpacing;
        _flowLayout.itemSize = _itemSize;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}
- (NSMutableArray <LBUploadPhotoModel *>*)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray <LBUploadPhotoModel *> alloc] init];
        [_dataArray addObject:[LBUploadPhotoModel new]];
    }
    return _dataArray;
}

- (instancetype)initWithTitleName:(NSString *)itemName
                         maxCount:(NSInteger)maxCount
                          OSSCode:(LBServiceOSSCode)OSSCode
                    photoViewType:(LBAddPhotoViewType)photoViewType {
    
    return [self initWithTitleName:itemName
                          itemSize:CGSizeMake(LBPicturesMargin, LBPicturesMargin)
                              left:15
                             right:15
                          maxCount:maxCount
                           OSSCode:OSSCode
                     photoViewType:photoViewType];

}

- (instancetype)initWithTitleName:(NSString *)itemName itemSize:(CGSize)itemSize left:(CGFloat)left right:(CGFloat)right maxCount:(NSInteger)maxCount OSSCode:(LBServiceOSSCode)OSSCode photoViewType:(LBAddPhotoViewType)photoViewType{
    if (self = [super init]) {
        _itemSize = itemSize;
        _left = left;
        _right = right;
        _OSSCode = OSSCode;
        _itemName = itemName;
        _maxCount = maxCount;
        _photoViewType = photoViewType;
        [self creatCollectionView];
    }
    return self;
}

- (NSMutableArray <LBUploadPhotoModel *> *)photoArray {
    NSMutableArray <LBUploadPhotoModel *> * array = [[NSMutableArray <LBUploadPhotoModel *> alloc] init];
    for (LBUploadPhotoModel * model in self.dataArray) {
        if (model.urlString.length || model.objectKey.length || model.image) {
            [array addObject:model];
        }
    }
    return array;
}

- (void)creatCollectionView {
    
    if (_photoViewType == LBAddPhotoTypeAuth) {
        [self.collectionView registerClass:[LBUploadPhotoCell class] forCellWithReuseIdentifier:@"LBUploadPhotoCell"];
    }
    else if (_photoViewType == LBAddPhotoTypeTask) {
        [self.collectionView registerClass:[LBTaskPhotoCell class] forCellWithReuseIdentifier:@"LBTaskPhotoCell"];
    }
    else if (_photoViewType == LBAddQualifiedBs) {
        [self.collectionView registerClass:[LBAddQualifiedBsCell class] forCellWithReuseIdentifier:@"LBAddQualifiedBsCell"];
    }
    
    [self addSubview:self.collectionView];

    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self);
        make.height.mas_equalTo(_itemSize.height);
        make.bottom.mas_equalTo(self.mas_bottom);
    }];
    
    [self updataViewHeight:self.dataArray];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_photoViewType == LBAddPhotoTypeAuth) {
        LBUploadPhotoCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LBUploadPhotoCell" forIndexPath:indexPath];
        
        __weak typeof(self)weakSelf = self;
        [cell setCellWithUploadPhotoModel:self.dataArray[indexPath.row] itemName:self.itemName indexPath:indexPath deleBlock:^(NSIndexPath *deIndexPath) {
            // 删除照片
            if (weakSelf.delePhotoBlock) {
                weakSelf.delePhotoBlock([weakSelf.dataArray objectAtIndex:deIndexPath.row],deIndexPath);
                return ;
            }
            [weakSelf delePhotoActionWithDeIndex:deIndexPath];
        } unEditable:self.unEditable];
        
        return cell;
    }
    else if (_photoViewType == LBAddPhotoTypeTask) {
        LBTaskPhotoCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LBTaskPhotoCell" forIndexPath:indexPath];
        
        __weak typeof(self)weakSelf = self;
        [cell setCellWithUploadPhotoModel:self.dataArray[indexPath.row] itemName:self.itemName indexPath:indexPath deleBlock:^(NSIndexPath *deIndexPath) {
            // 删除照片
            if (weakSelf.delePhotoBlock) {
                weakSelf.delePhotoBlock([weakSelf.dataArray objectAtIndex:deIndexPath.row],deIndexPath);
                return ;
            }
            [weakSelf delePhotoActionWithDeIndex:deIndexPath];
        } unEditable:self.unEditable];
        
        return cell;
    }
    else if (_photoViewType == LBAddQualifiedBs) {
        LBAddQualifiedBsCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LBAddQualifiedBsCell" forIndexPath:indexPath];
        
      __weak typeof(self)weakSelf = self;
        [cell setCellWithUploadPhotoModel:self.dataArray[indexPath.row] itemName:self.itemName indexPath:indexPath deleBlock:^(NSIndexPath *deIndexPath) {
            // 删除照片
            if (weakSelf.delePhotoBlock) {
                weakSelf.delePhotoBlock([weakSelf.dataArray objectAtIndex:deIndexPath.row],deIndexPath);
                return ;
            }
            [weakSelf delePhotoActionWithDeIndex:deIndexPath];
        } unEditable:self.unEditable];
  
        return cell;
    }
    return nil;
}

- (void)delePhotoActionWithDeIndex:(NSIndexPath * )deIndexPath {

    LBUploadPhotoModel * model = self.dataArray.lastObject;
    if (self.dataArray.count == self.maxCount && (model.urlString.length || model.objectKey.length || model.image)) {
        [self.dataArray addObject:[LBUploadPhotoModel new]];
    }
    [self.dataArray removeObjectAtIndex:deIndexPath.row];
    [self updataViewHeight:self.dataArray];
    [self.collectionView reloadData];
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self)weakSelf = self;
    LBUploadPhotoModel * photoModel = self.dataArray[indexPath.row];
    
    if (photoModel.urlString.length || photoModel.objectKey.length || photoModel.image) {
        NSMutableArray * browserArray = [[NSMutableArray alloc] init];
        for (LBUploadPhotoModel * model in self.dataArray) {
            if (model.urlString.length) {
                [browserArray addObject:model.urlString];
            }
            else if (model.image){
                [browserArray addObject:model.image];
            }
        }
        NSMutableArray *array = [NSMutableArray new];
        for (id obj in browserArray) {
            if ([obj isKindOfClass:[NSString class]]) {
                LBPhoto *photo = [[LBPhoto alloc]initWithURLString:obj];
                [array addObject:photo];
            }
            else if ([obj isKindOfClass:[UIImage class]]){
                LBPhoto *photo = [[LBPhoto alloc]initWithImage:obj];
                [array addObject:photo];
            }

        }

        [LBPhotoBrowser showWithPhotos:array selectIndex:indexPath.row sourceImageViewClosure:^UIImageView *(NSInteger index) {
            LBUploadPhotoCell *cell = (LBUploadPhotoCell*)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
            return cell.bgImageView;
        }];
    }
    else{
        [LBActionSheet showImagePickerInView:self.superview completion:^(NSDictionary<NSString *,id> *info) {
            
            UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
            
            UIImage * newImage = [LBActionSheet fixOrientation:image];
            
            while (newImage.size.width > 1500) {
                newImage = [self imageWithImageSimple:newImage scaledToSize:CGSizeMake(newImage.size.width * 0.5, newImage.size.height * 0.5)];
            }
            
            NSData *imgData = UIImageJPEGRepresentation(newImage, 1);
            
            // 5M
            while (imgData.length / (1024.0 * 1024) > 5) {
                imgData = UIImageJPEGRepresentation(newImage, 0.5);
                newImage = [UIImage imageWithData:imgData];
            }
            
            LBUploadPhotoModel * model = [[LBUploadPhotoModel alloc] init];
            
            if (image !=nil) {
                //获取图片的名字
                __block NSString* imageFileName;
                NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
                ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset) {
                    ALAssetRepresentation *representation = [myasset defaultRepresentation];
                    imageFileName = [representation filename];
                    model.imageFileName = imageFileName;
                };
                
                ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
                [assetslibrary assetForURL:imageURL
                               resultBlock:resultblock
                              failureBlock:nil];
            }
            
            [LBLoadingView showWithText:@"正在上传..."];
            
            [LBOSSService getOSSUploadDataWithFile:imgData fileType:weakSelf.OSSCode contentType:LBOSSContentTypePNG progressBlock:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
                
                
                
            } uploadSuccess:^(NSString *objectKey) {
                
                model.image =  [UIImage imageWithData:imgData];
                model.objectKey = objectKey;
                
            } getUrlSuccess:^(NSString *UrlString) {
                // 获取到图片的url
                
                model.urlString = UrlString;
                
                if (weakSelf.dataArray.count < weakSelf.maxCount) {
                    
                    [weakSelf.dataArray insertObject:model atIndex:weakSelf.dataArray.count - 1];
                }
                else{
                    weakSelf.dataArray[weakSelf.dataArray.count - 1] = model;
                }
                [weakSelf updataViewHeight:weakSelf.dataArray];
                [weakSelf.collectionView reloadData];
                
                
                [LBLoadingView dismiss];
                
            } failure:^(NSError *error, NSString *message) {
                [LBLoadingView dismiss];
            }];
        }];
    }
}
- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (void)updataViewHeight:(NSMutableArray *)dataArray {
    
    self.viewHeight = [self heightForCollectionViewWithItemCount:_dataArray.count];

    [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.viewHeight);
    }];

    NSMutableArray * array = [[NSMutableArray alloc] init];
    
    if (dataArray.count) {
        
        for (int i = 0 ; i < dataArray.count - 1 ; i ++) {
            
            [array addObject:dataArray[i]];
        }
        
        LBUploadPhotoModel * model = self.dataArray.lastObject;
        
        if (model.urlString.length || model.objectKey || model.image) {
            
            [array addObject:model];
        }
        
    }
    
    !self.updataViewHeightBlock ? :self.updataViewHeightBlock(array);
}

- (CGFloat)heightForCollectionViewWithItemCount:(NSInteger)itemCount
{
    NSInteger row = 1;
    
    CGFloat width = [[UIScreen mainScreen] bounds].size.width - _left - _right;
    
    NSInteger rowCount = (NSInteger)width / (_itemSize.width + minimumInteritemSpacing);
    
    if (rowCount * (_itemSize.width + minimumInteritemSpacing) + _itemSize.width <= width) {
        rowCount ++;
    }
    if (itemCount > rowCount) {
        NSInteger addRow = itemCount / rowCount;
        row += addRow;
        if (itemCount % rowCount == 0) {
            row -= 1;
        }
    }
    return row * _itemSize.height + (row - 1) * minimumLineSpacing + 2;
}
- (void)setAddPhotoViewWithImageUrlArray:(NSArray *)imageUrlArray {
    
    self.dataArray = [[NSMutableArray alloc] init];
    if (imageUrlArray.count) {
        if ([imageUrlArray.firstObject isKindOfClass:[LBUploadPhotoModel class]]) {
            self.dataArray = [NSMutableArray arrayWithArray:imageUrlArray];
        }
        else {
            for (id imageUrl in imageUrlArray) {
                LBUploadPhotoModel * model = [[LBUploadPhotoModel alloc] init];
                if ([imageUrl isKindOfClass:[UIImage class]]) {
                    model.image = imageUrl;
                }
                else {
                    model.urlString = imageUrl;
                }
                [self.dataArray addObject:model];
            }
        }
    }
    if (self.dataArray.count < _maxCount) {
        [self.dataArray addObject:[LBUploadPhotoModel new]];
    }
    
    if (self.unEditable) {
        LBUploadPhotoModel * model = self.dataArray.lastObject;
        
        if (!model.urlString.length && !model.objectKey.length && !model.image) {
            
            [self.dataArray removeObject:model];
        }

    }
    
    [self updataViewHeight:self.dataArray];
    [self.collectionView reloadData];
}



-(void)reloadData
{
    [self.collectionView reloadData];
}
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)resetServerOSSCode:(LBServiceOSSCode)ossCode
{
    _OSSCode = ossCode;
}

- (void)setUnEditable {
    
    self.unEditable = YES;
    
    LBUploadPhotoModel * model = self.dataArray.lastObject;
    
    if (!model.urlString.length && !model.objectKey.length && !model.image) {
        
        [self.dataArray removeObject:model];
    }
    
    [self updataViewHeight:self.dataArray];
    
    [self.collectionView reloadData];
}


@end
